// 螺旋矩阵

package Leetcode;

import java.util.ArrayList;
import java.util.List;

class solution_054 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<int[]> drection = new ArrayList<int[]>();
        drection.add(0, new int[] { 0, 1 });
        drection.add(1, new int[] { 1, 0 });
        drection.add(2, new int[] { 0, -1 });
        drection.add(3, new int[] { -1, 0 });
        List<int[]> bound = new ArrayList<>();
        bound.add(0, new int[] { 1, matrix[0].length - 1 }); // 1表示列，0表示行
        bound.add(1, new int[] { 0, matrix.length - 1 });
        bound.add(2, new int[] { 1, 0 });
        bound.add(3, new int[] { 0, 0 });
        int num = matrix.length * matrix[0].length;
        int[] start = new int[] { 0, 0 };
        int currentDerection = 0;
        List<Integer> result = new ArrayList<>();
        while (num-- != 0) {
            result.add(matrix[start[0]][start[1]]);
            boolean max = (currentDerection == 0 | currentDerection == 1) & (start[bound.get(currentDerection)[0]]
                    + drection.get(currentDerection)[bound.get(currentDerection)[0]] > bound.get(currentDerection)[1]);
            boolean min = (currentDerection == 2 | currentDerection == 3) & (start[bound.get(currentDerection)[0]]
                    + drection.get(currentDerection)[bound.get(currentDerection)[0]] < bound.get(currentDerection)[1]);
            if (max | min) {
                if (currentDerection == 1 | currentDerection == 2)
                    bound.get((currentDerection + 3) % 4)[1]--;
                if (currentDerection == 0 | currentDerection == 3)
                    bound.get((currentDerection + 3) % 4)[1]++;
                currentDerection = (currentDerection + 1) % 4;
            }
            start[0] = start[0] + drection.get(currentDerection)[0];
            start[1] = start[1] + drection.get(currentDerection)[1];
        }
        return result;
    }

}

public class Solution054 {

}
